<?php

declare(strict_types=1);

namespace App\CustHub\Service;

use App\CustHub\Mapper\ChSubUserMapper;
use App\CustHub\Mapper\ChUserExtMapper;
use Hyperf\Cache\Annotation\CacheEvict;
use Hyperf\Di\Annotation\Inject;
use Mine\Abstracts\AbstractService;
use Mine\Event\UserAdd;
use Mine\Exception\NormalStatusException;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class ChSubUserService extends AbstractService
{
    public $mapper;

    #[Inject]
    protected ChUserExtMapper $userExtMapper;

    public function __construct(ChSubUserMapper $mapper)
    {
        $this->mapper = $mapper;
    }

    /**
     * 新增用户.
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function save(array $data): mixed
    {
        if ($this->mapper->existsByAccount($data['account'])) {
            throw new NormalStatusException('账号已存在');
        }

        $id = $this->mapper->save($this->handleData($data));
        return $id;
    }

    public function getInfo(array $params)
    {
        $mode =  $this->mapper->findById($params['id']);
        unset($mode->password);
        $mode->role_id = $mode->roles()->pluck('id')->first();
        return $mode;
    }

    /**
     * 更新用户信息.
     */
    #[CacheEvict(prefix: 'commonLoginInfo', value: 'userId_#{id}')]
    public function update(mixed $id, array $data): bool
    {
        $user = $this->mapper->findById($id);
        if(empty($user) || $user->parent_id == 0){
            throw new NormalStatusException('请选择员工');
        }

        if ($this->mapper->existsByAccount($data['account'],$id)) {
            throw new NormalStatusException('账号已存在');
        }

        return $this->mapper->update($id, $this->handleData($data));
    }

    /**
     * 处理提交数据.
     * @param mixed $data
     */
    protected function handleData(array $data): array
    {
        if (!is_array($data['role_id'])) {
            $data['role_ids'] = explode(',', $data['role_id']);
        }

        if(empty($data['password'])){
            unset($data['password']);
        }

        return $data;
    }

    /**
     * 设置分组
     * @param array $data
     * @return bool
     */
    public function setGroup(array $data): bool
    {
        $ids = json_decode($data['ids'],true);
        return $this->userExtMapper->setGroup($ids, (int)$data['group_id']);
    }

    /**
     * 用户修改密码
     */
    public function modifyPassword(array $params): bool
    {
        return $this->mapper->initUserPassword(user()->getId(), $params['newPassword']);
    }
}